Write a MongoDB aggregation query to group and calculate the average of a field in a collection.
home / developersection / forums / write a mongodb aggregation query to group and calculate the average of a field in a collection.
Write a MongoDB aggregation query to group and calculate the average of a field in a collection.
Aryan Kumar
27-Jul-2023Sure, here is a MongoDB aggregation to group and calculate the average of a field in a collection:
This aggregation will group the documents in the collection by the value of the
fieldfield. For each group, the average of thefieldfield will be calculated and stored in theaveragefield.For example, if the collection contains the following documents:
The aggregation will produce the following output:
The
_idfield in the output documents is the value of thefieldfield in the original documents. Theaveragefield is the average of thefieldfield in the documents that were grouped together.To run this aggregation, you can use the
mongoshell or a MongoDB driver. For example, to run the aggregation using themongoshell, you would use the following command:mongo <database> <collection> --eval "db.collection.aggregate([{ $group: { _id: '$field', average: { $avg: '$field' } } }])"
Replace
<database>and<collection>with the name of the database and collection that you want to use.